package tasks

import (
	"itodo/core/localwrap"
	"time"

	"github.com/RocksonZeta/hubx"
	"github.com/go-redis/redis/v7"
)

var log = localwrap.GetLogger().Fork("itodo/ws/taskcenter", "TaskCenter")

type TaskCenter struct {
	Id          int //gameid
	hub         *hubx.Hubx
	Groups      map[int][]*hubx.Client // groupId : clients
	Observers   map[int][]*hubx.Client // groupId : clients, group observers
	Subscribers map[int][]*hubx.Client // groupId : clients, group subscribers
}

type TaskCenterOptions struct {
	Id int
	hubx.RedisOptions
	red *redis.Client
}

func NewTaskCenter(options TaskCenterOptions) (*TaskCenter, error) {
	log.Trace().Func("NewTaskCenter").Interface("options", options).Send()
	hub, err := hubx.New(hubx.Options{
		TickerPeriod: 1 * time.Second,
		ChannelSize:  options.ChannelSize,
	})
	if err != nil {
		return nil, err
	}
	bc, err := hubx.NewRedisBroadcaster(hub, options.RedisOptions)
	if err != nil {
		return nil, err
	}
	hub.SetBroadcaster(bc)
	r := &TaskCenter{
		hub: hub,
	}
	r.initListeners()
	bc.Start()
	hub.Start()

	return r, nil
}
func (t *TaskCenter) Hub() *hubx.Hubx {
	return t.hub
}

func (t *TaskCenter) initListeners() {
	log.Trace().Func("initListeners").Send()
	t.hub.AfterJoin = t.afterJoin
	t.hub.OnWs("play", t.onWsPlay)
	t.hub.OnWsDefault(t.onWsDefault)
	t.hub.OnDefault(t.onDefault)
}

func (t *TaskCenter) onWsDefault(client *hubx.Client, msg hubx.PartialMessage) {
	log.Trace().Func("onWsDefault").Str("Subject", msg.Subject).Send()
	t.hub.Broadcast(msg.Subject, msg.Data)
}
func (t *TaskCenter) onDefault(msg hubx.PartialMessage) {
	log.Trace().Func("onDefault").Str("Subject", msg.Subject).Send()
	t.hub.BroadcastWs(msg.Subject, msg.Data)
	// g.hub.SendWs()
}
func (t *TaskCenter) afterJoin(client *hubx.Client) {
	log.Trace().Func("afterJoin").Send()
	msg := initMsg{}

	t.hub.SendWs("init", msg, client)
	t.hub.Broadcast("join", getUser(client))
}

func (t *TaskCenter) onWsPlay(client *hubx.Client, msg hubx.PartialMessage) {
	log.Trace().Func("onWsPlay").Send()
	t.hub.Broadcast("play", nil)
}

func (t *TaskCenter) onPlay(msg hubx.PartialMessage) {
	log.Trace().Func("onPlay").Send()
	t.hub.BroadcastWs(msg.Subject, msg.Data)
}
